package com.sjq.est.controller;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sjq.est.common.util.BaseController;
import com.sjq.est.common.util.ResultUtil;
import com.sjq.est.config.WechatLoginProperties;
import com.sjq.est.constants.Constants;
import com.sjq.est.dto.Result;
import com.sjq.est.dto.TokenDTO;
import com.sjq.est.dto.UsersInfoDTO;
import com.sjq.est.entity.Users;
import com.sjq.est.param.SmsLoginParam;
import com.sjq.est.service.TokenService;
import com.sjq.est.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;
import java.lang.String;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController extends BaseController {

    @Autowired
    private WechatLoginProperties wechatLoginProperties;

    @Autowired
    private UsersService usersService;

    @Autowired
    private TokenService tokenService;

    @GetMapping("/api/user/login/wechat")
    public void toWechatLogin() throws IOException {
        StringBuilder builder = new StringBuilder(wechatLoginProperties.getLoginUrl());
        builder.append("appid=").append(wechatLoginProperties.getAppId());
        builder.append("&redirect_uri=").append(wechatLoginProperties.getRedirectUrl());
        builder.append("&response_type=code&scope=snsapi_login&state=111111#wechat_redirect");
        response.sendRedirect(builder.toString());
    }

    @GetMapping("/api/user/login/wechatcallback")
    public void wechatcallback(String code) throws IOException {
        //获取tokenurl
        StringBuilder getTokenUrl = new StringBuilder("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
        getTokenUrl.append(wechatLoginProperties.getAppId());
        getTokenUrl.append("&secret=").append(wechatLoginProperties.getAppSecret());
        getTokenUrl.append("&code=").append(code).append("&grant_type=authorization_code");
        String tokenurl = new String(getTokenUrl);

        //通过RestTemplate发送http请求
        RestTemplate restTemplate = new RestTemplate();
        String tokenInfoJsonString = restTemplate.getForObject(tokenurl, String.class);
        JSONObject tokenInfoJsonObj = new JSONObject(tokenInfoJsonString);

        //获取返回的access_token和openid
        String access_token = tokenInfoJsonObj.getStr("access_token");
        String openid = tokenInfoJsonObj.getStr("openid");

        //3. 通过openid查询用户是否已经存在于系统中
        Users users = usersService.findByOpenId(openid);
        //4. 如果不存在，就进行自动注册
        if (users == null) {
            // 获取用户的信息
            String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={1}&openid={2}";
            String userInfoJsonString = restTemplate.getForObject(getUserInfoUrl, String.class, access_token, openid);
            JSONObject userInfoJsonObj = new JSONObject(userInfoJsonString);
            users = new Users();
            users.setUserName(userInfoJsonObj.getStr("nickname"));
            users.setSex(userInfoJsonObj.getInt("sex"));
            users.setIsAuthentication(Constants.EST_NOT);
            users.setFaceUrl(userInfoJsonObj.getStr("headimgurl"));
            users.setOpenId(openid);
            Date createdTime = new Date();
            users.setCreatedTime(createdTime);
            users.setUpdatedTime(createdTime);
            users.setIsDelete(Constants.EST_NOT);
            usersService.registe(users);
        }
        //5. 根据登录的用户信息，生成会话信息
        TokenDTO tokenDTO = tokenService.generateToken(users);
        tokenService.saveToken(tokenDTO.getToken(),users);
        //6. 返回会话信息
        Map<String,Object> tokenUserInfo = new HashMap<>();
        tokenUserInfo.put("token",tokenDTO.getToken());
        tokenUserInfo.put("userInfo",users.getUserName());
        String tokenString = JSONUtil.toJsonStr(tokenUserInfo);

        // 如果url中有一些特殊字符或中文字符的话，要进行编码处理
        String encodeTokenString = URLEncoder.encode(tokenString, "utf-8");

        // 7. 重定向到前端的相关页面
        //return ResultUtil.success();
        String loginSuccessURL="http://localhost:8081/redirect?token="+ encodeTokenString;
        response.sendRedirect(loginSuccessURL);
    }

    @PostMapping("/api/user/login/sms")
    public Result<TokenDTO> smsLogin(@Valid SmsLoginParam loginParam) {
        TokenDTO tokenDTO = usersService.smsLogin(loginParam);

        return ResultUtil.success(tokenDTO);
    }

    @PostMapping("/api/user/info")//获取用户信息根据token
    public Result<UsersInfoDTO> getUserInfo(){
        String token = request.getHeader("token");
        UsersInfoDTO usersInfoDTO = usersService.getUserInfoByToken(token);
        return ResultUtil.success(usersInfoDTO);
    }

    /**
     * 总结手机短信登陆：用户输入手机号，获取验证码，现在redis里根据手机号查找
     * @return
     */
    @PostMapping("/api/user/logout")
    public Result<Void> logout() {
        String token = request.getHeader("token");
        usersService.logout(token);
        return ResultUtil.success();
    }

}
